package com.hengtiansoft.lfy.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.UpdateEntity;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.FileUtil;
import com.hengtiansoft.lfy.utils.ScreenUtils;
import com.hengtiansoft.lfy.widget.MyToast;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * 关于龙翻译界面
 */
public class AboutActivity extends BaseActivity implements OnClickListener {
    private static String TAG = "AboutActivity";
    private RelativeLayout mRlEvaluate;
    private RelativeLayout mRlFeedback;
    private RelativeLayout mRlVersions;
    private RelativeLayout mRlProtocol;
    private TextView mTvVersion;
    private Context mContext;
    private ProgressDialog pd;
    private boolean hasSendJson = false;
    private String mAppDownloadUrl = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_about);
        initView();
        setListener();
    }

    private void initView() {
        pd = new ProgressDialog(mContext, ProgressDialog.THEME_HOLO_LIGHT);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(true);
        mRlProtocol = (RelativeLayout) findViewById(R.id.rl_copy);
        mRlEvaluate = (RelativeLayout) findViewById(R.id.rl_me_collect);
        mRlFeedback = (RelativeLayout) findViewById(R.id.rl_feedback);
        mRlVersions = (RelativeLayout) findViewById(R.id.rl_versions);
        mTvVersion = (TextView) findViewById(R.id.tv_version);
        mTvVersion.setText("V" + ScreenUtils.getVersion(mContext));
    }

    private void setListener() {
        mRlEvaluate.setOnClickListener(this);
        mRlFeedback.setOnClickListener(this);
        mRlVersions.setOnClickListener(this);
        mRlProtocol.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_me_collect:
                try {
                    Toast.makeText(mContext, getString(R.string.app_marketplace_evaluate), Toast.LENGTH_LONG).show();
                    Uri uri = Uri.parse("market://details?id=" + getPackageName());
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }catch (Exception ex){
                    MyToast.show(self,getString(R.string.tiaozhuanerr));
                }

                break;
            case R.id.rl_feedback:
                LayoutInflater factory = LayoutInflater.from(mContext);// 提示框
                final View dialogview = factory.inflate(R.layout.dialog_feedback,
                        null);// 这里必须是final的
                final EditText edit = (EditText) dialogview
                        .findViewById(R.id.tv_dialog_new_userpwd);// 获得输入框对象
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle(getString(R.string.feedback)).setView(dialogview).setNegativeButton(getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                closeDialog(dialog, true);
                            }
                        });
                builder.setPositiveButton(getString(R.string.ok),
                        new DialogInterface.OnClickListener() {

                            public void onClick(final DialogInterface dialog,
                                                int which) {
                                if (edit.getText().toString().equals("")) {
                                    //edit.setError(getString(R.string.introduce_remarks));
                                    Toast.makeText(mContext, getString(R.string.introduce_remarks), Toast.LENGTH_SHORT).show();
                                    closeDialog(dialog, false);
                                } else {
                                    pd.setMessage(getString(R.string.commiting));
                                    pd.show();
                                    String content= edit.getText().toString();
                                    String phonetype=ScreenUtils.getMobileModelInfo();
                                    String systemtype=ScreenUtils.getMobileRELEASEInfo();
                                    if (!hasSendJson)
                                        feedBack(content,phonetype,systemtype);
                                    closeDialog(dialog, true);
                                }
                            }
                        });
                builder.show();
                break;
            case R.id.rl_versions:
                if (CommonUtils.isNetWorkConnected(mContext)) {
                    Log.i(TAG, "正在检查版本更新");
                    pd.setMessage(getString(R.string.version_check));
                    pd.show();
                    update();
                } else {
                    Toast.makeText(mContext, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.rl_copy:
                startActivity(new Intent(mContext, ProtocolActivity.class));
                break;
            default:
                break;
        }
    }
    /**
     * dialog的关闭
     *
     * @param dialog
     * @param isClose
     */
    void closeDialog(DialogInterface dialog, boolean isClose) {
        try {
            Field field = dialog.getClass().getSuperclass()
                    .getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, isClose);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /***
     * 建议提交请求
     * @param content
     * @param phonetype
     * @param systemtype
     */
    public void feedBack(String content,String phonetype,String systemtype){
         NetHelper.feedback(self ,content,phonetype,systemtype ,new NetUtils.NetCallBack<ServiceResult>() {
                     @Override
                     public void success(ServiceResult rspData) {
                         int code = 1;
                         String message = null;
                         message = rspData.getMessage();
                         code = rspData.getRetcode();
                         if (code == 0) {
                             Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                     .show();
                         } else {
                             Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                     .show();
                         }
                         pd.dismiss();
                         hasSendJson = false;

                     }
                     @Override
                     public void failed(String msg) {
                         MyToast.show(self, msg);
                         hasSendJson = false;
                         pd.dismiss();

                     }
                 }, ServiceResult.class);
    }


    /**
     * 检查版本更新
     */
    private void update() {
        String version="v" + ScreenUtils.getVersion(self);
        NetHelper.updateApi(self, version, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                pd.dismiss();
                UpdateEntity info = (UpdateEntity) rspData;
                int code = info.getRetcode();
                String message = info.getMessage();
                if (code == 0) {
                    String data = info.getData();
                    mAppDownloadUrl = data;
                    // 弹出对话框通知用户更新程序
                    runOnUiThread(new Runnable() {
                        public void run() {
                            showUpdataDialog();
                        }
                    });
                }

            }
            @Override
            public void failed(String msg) {
                pd.dismiss();
                MyToast.show(self, msg);

            }
        }, UpdateEntity.class);
    }

    // 弹出对话框通知用户更新程序
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new Builder(this);
        builer.setTitle(getString(R.string.version_update_title));
        builer.setMessage(getString(R.string.version_update_message));
        // 当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton(getString(R.string.confirm),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(TAG, "<showUpdataDialog> -- 下载apk");
                        downLoadApk();
                    }

                });
        // 当点取消按钮时进行登录
        builer.setNegativeButton(getString(R.string.cancel),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // 若服务器上的主版本号或次版本号大于当前的主版本号或次版本号，则按取消时，直接退出应用
                        // finish();
                        dialog.dismiss();

                    }

                });
        AlertDialog dialog = builer.create();
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        dialog.show();
    }

    // 从服务器中下载APK
    protected void downLoadApk() {
        final ProgressDialog pd; // 进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage(getString(R.string.version_updating));
        pd.setCanceledOnTouchOutside(false);
        pd.show();

        new Thread() {
            @Override
            public void run() {
                try {
                    File file = FileUtil.getFileFromServer(mContext,
                            mAppDownloadUrl, pd, Constants.APK_NAME);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); // 结束掉进度条对话框
                } catch (Exception e) {
                    pd.dismiss();
                    e.printStackTrace();
                }
            }
        }.start();
    }

    // 安装apk
    protected void installApk(File file) {
        if (file == null) {
            // showToast(mContext, getString(R.string.version_update_error),
            // Toast.LENGTH_SHORT);
            return;
        }
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
